<template>
  <div class="add_dialog">
    <el-dialog title="提交问题反馈" :visible.sync="dialogVisible" :close-on-click-modal="false"  width="1000px" @close="close" :close-on-press-escape="false">
      <div class="add-edit-box">
        <div class="flex" v-loading="loading">
          <div class="form-box" @click="boxradioIsShow = ''">
            <el-form ref="form" :model="form" :inline="false" :rules="rules" label-width="100px" class="demo-ruleForm">
                <el-form-item label="反馈类型" prop="type">
                  <el-select v-model="form.type">
                    <el-option v-for="(item,key) in typeObj" :key="key" :value="item">{{item}}</el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="反馈意见" prop="content" class="">
                  <el-input type="textarea"  v-model="form.content" placeholder="请输入反馈意见，最多800个字" maxlength="800" show-word-limit :disabled="isView" :rows="6" style="width:600px" />
                </el-form-item>
                <el-form-item label="联系电话" prop="lianxifangshi">
                  <el-input v-model="form.lianxifangshi" placeholder="请输入联系电话" :disabled="isView" />
                </el-form-item>

                
                <el-form-item label="上传视频">
                  <el-upload class="upload-demo" :headers="headers" action="#" :before-upload="beforeUploadVideo" :http-request="uploadVideoFn" :on-success="handleVideoSuccess" :limit="1" accept="video/mp4, video/mpeg4" v-if="!form.video">
                    <img class="uploadbg" src="https://imgage.maimaihao.com/yuduhulian/erp/static/img/uploadBg/videoBg.png" alt="" />
                  </el-upload>
                  <div class="video-view radius flex" v-if="form.video">
                    <video controls :src="form.video"></video>
                    <span class="el-icon-delete" @click="handleVideoRemove"></span>
                  </div>
                  <div class="colorred font12">视频格式:MP4格式 尺寸比例:16:9;请上传30MB以内的视频</div>
                </el-form-item>
                <el-row>
                  <el-form-item label="图片" prop>
                    <div class="">
                      <!-- 自定义拖拽排序 -->
                      <draggable v-model="imgFileList">
                        <transition-group class="uploader">
                          <div v-for="(item, index) in imgFileList" :key="item.url" class="upload-list">
                            <img v-if="item.url" style="width: 100%; height: 100%" :src="
                                item.url.indexOf('blob:') > -1
                                  ? item.response && item.response.data
                                    ? item.response.data.filePath
                                    : item.url
                                  : item.url
                              " />
                            <img class="imgs" v-if="item.url" style="width: 30px" src="../../../assets/img/shangchuan.png" alt="" />
                            <div class="icon-container">
                              <span v-if="item.url" @click="handlePreviewNew(index)">
                                <i class="el-icon-zoom-in"></i>
                              </span>
                              <span v-if="
                                  item.url &&
                                  (!isView || (isEdit && form.saleState != 1))
                                " @click="handleRemove(item.url)">
                                <i class="el-icon-delete"></i>
                              </span>
                            </div>
                          </div>
                        </transition-group>
                      </draggable>
                      <el-upload :action="uploadImgUrl" :file-list="imgFileList" list-type="picture-card" :show-file-list="false" :on-preview="handlePictureCardPreview" :on-exceed="uploadNumber" :multiple="true" :drag="true" :on-success="handleUploadSuccess" :limit="100"
                                 accept="image/png, image/jpeg" :on-remove="handleRemove" :http-request="uploadImgs" :disabled="isView">
                        <img class="uploadbg" src="https://imgage.maimaihao.com/yuduhulian/erp/static/img/uploadBg/infoImgBg.png" alt="" />
                      </el-upload>
                    
                    </div>
                  
                  </el-form-item>
                </el-row>
            </el-form>
          </div>
        </div>
        <div class="center">
          <el-button class="font16" plain type="" @click="close">关闭 </el-button>
          <el-button  type="primary" @click="submitForm" :loading="loading">确认提交</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import fankuiApi from "@/api/PCWebImages/fankui.js";
import { getToken } from "@/utils/auth";
import { spliceUploadHandle } from "@/api/spliceUpload.js";
import ImageCompressor from "image-compressor.js";
import { postUpload, creatrandomStr, closerandomStr } from "@/api/upload";
export default {
  name: "",
  components: {
    draggable
  },
  data() {
    return {
      loading: false,
      isEdit: false,
      dialogVisible: false,
      btnLoading: false,
      isView:false,
      form: {
      
      },
    
      imgFileList: [],
      // imgShowList: [],
      titleImgList: [],
      videoList: [],

      typeObj:{
        1:'改进建议',
        2:'问题反馈',
        3:'投诉举报',
      },
     
      uploadImgUrl: "",
      uploadVideoUrl: "",
      headers: {},
     
      newImages: [], //编辑的时候新增加的图片，新增的时候新增加的图片
     
      rules: {
        title: [{ required: true, message: "请输入商品标题", trigger: "blur" }],
       
      },
    };
  },
  computed: {
    tenantInfo() {
      return this.$store.getters.shopInfo;
    },
  },
  created() {
    this.headers = {
      Authorization: "Bearer " + getToken(),
    };
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
    this.uploadVideoUrl = process.env.VUE_APP_BASE_API + "/upload/video";
   
  },
  methods: {
    open(flag, id) {
      this.dialogVisible = true;
      this.isEdit = false;
      this.form = {}
    },
  

    // 重置
    reset() {
      this.$refs["form"].resetFields();
    },
  
    // 上传视频前
    beforeUploadVideo(file) {
     
      if (file.size / 1024 / 1024 > 30) {
        this.$message.error("上传的视频不能超过30MB！请处理后再传！");
        return false;
      } else {
        return true;
      }
    },
    // 上传视频
    async uploadVideoFn(file) {
      //上传到后台
      try {
        let uploadImg = await spliceUploadHandle(file.file);
        // console.log("%c Line:157 🥑 uploadImg", "color:#b03734", uploadImg);
        file.data = {
          filePath: uploadImg.filePath,
          fileName: uploadImg.fileName,
        };
        file.code = 200;
        return file;
      } catch {
        file.code = 500;
        return file;
      }
    },

    /**以下是图片上传相关 */
    uploadNumber(file, fileList) {
      //限制图片数量
      this.$modal.msgError("最多只能上传50张图片");
    },

    handleVideoSuccess(res, file) {
      // console.log("%c Line:857 🍤 res", "color:#ed9ec7", res);
      if (res.code == 200) {
        this.$set(this.form, "video", res.data.filePath);
        this.$set(this.form, "videoName", res.data.fileName);
      }
    },
    handleVideoRemove() {
      this.$set(this.form, "video", null);
      this.$set(this.form, "videoName", null);
    },
    // 压缩图片
    compressImage(file) {
      return new Promise((resolve, reject) => {
        if (file.size / 1024 / 1024 > 1) {
          new ImageCompressor(file.file, {
            quality: 0.6,
            checkOrientation: false,
            // width:1920,
            success(result) {
              resolve(result);
            },
            error(e) {
              reject();
            },
          });
        } else {
          resolve(file.file);
        }
      });
    },
    // 上传图片
    async uploadImgs(file) {
      // 获取压缩后的文件流
      let compreeBolb = await this.compressImage(file);
      // ////console.log("%c Line:468 🎂 压缩后compreeBolb", "color:#33a5ff", compreeBolb);
      const formData = new FormData();
      formData.append("file", compreeBolb); //压缩后的文件会自动转换成二进制文件流类型
      //上传图片到后台
      try {
        let uploadImg = await postUpload(formData);
        file.data = {
          filePath: uploadImg.msg,
        };
        file.code = 200;
        return file;
      } catch {
        file.code = 500;
        return file;
      }
    },
    // 详情图片上传成功
    handleUploadSuccess(res, file, fileList) {
      if (fileList.every((item) => item.status == "success")) {
        let tempArr = this.imgFileList.map((m) => {
          return m.url;
        });
        fileList.forEach((t) => {
          if (
            t.url.indexOf("blob:") > -1 &&
            t.response &&
            t.response.data &&
            t.response.data.filePath
          ) {
            if (!tempArr.includes(t.response.data.filePath)) {
              this.imgFileList.push({
                url: t.response.data.filePath,
                name: "",
              });
            }
            return true;
          }
        });
      }
    },
    // 详情图片删除
    handleRemove(url) {
      // ////console.log("%c Line:495 🍎 response", "color:#4fff4B", response);
      const that = this;
      // 1.获取将要删除图片的临时路径
      // const filePath = response.url;
      // 2.找到图片对应的索引值
      this.imgFileList.forEach(function (element, key) {
        if (element.url === url) {
          that.imgFileList.splice(key, 1); //回显的图片
        }
      });
      // this.imgShowList.forEach(function (element, key) {
      //   if (element.url === filePath) {
      //     that.imgShowList.splice(key, 1); //回显的图片
      //   }
      // });
      this.newImages.forEach(function (element, key) {
        if (element.url === url) {
          that.newImages.splice(key, 1); //新上传的图片
        }
      });
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    // 处理图片预览效果
    handlePreviewNew(index) {
      let arr = [];
      this.imgFileList.map((item) => {
        arr.push(item.url);
      });
      this.$viewerApi({
        images: arr,
        options: {
          initialViewIndex: index,
        },
      });
    },
   

    // 提交
    submitForm(formName,flag) {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          // 二次确认
          this.$confirm(
            `确定提交吗？`,
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(() => {
              this.submitFormSure();
            })
            .catch(() => {});
        } else {
          this.$alert("请填写完整！");
        }
      });
    },
    // 发布活修改确认
    submitFormSure() {
      // 拼接新上传的图片 this.newImages
   
      if (this.newImages && this.newImages.length) {
        let newArr = [];
        this.newImages.forEach((img) => {
          newArr.push({
            name: img.name,
            url: img.response.data.filePath,
          });
        });
        this.form.img = this.imgFileList.concat(newArr);
      } else {
        this.form.img = this.imgFileList;
      }
      this.form.img = JSON.stringify(this.form.img)
      this.form.tenantName = this.tenantInfo&&this.tenantInfo.tenantName?this.tenantInfo.tenantName:''
        fankuiApi.problemFeedbackAdd(this.form).then((response) => {
          this.dialogVisible = false;
          this.$modal.msgSuccess("提交成功");
          this.reset();
          this.$parent.getList()
        });
    },
    close() {
      this.reset()
      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped lang="scss">
.video-view {
  width: 324px;
  height: $uploadHeight;
  // position: relative;
  // background: #409eff;
  align-items: flex-start;
  .el-icon-delete {
    width: 30px;
    height: 30px;
    flex-shrink: 0;
    font-size: 20px;
    margin-left: 10px;
    color: #333;
    cursor: pointer;
    // &:hover {
    //   color: $primary;
    // }
    // color: $fff;
  }
  video {
    width: 294px;
    height: 165px;
    border-radius: 10px;
  }
}
::v-deep .form-box .el-upload-dragger {
  width: $uploadWidth;
  height: $uploadHeight;
  border: none;
}
::v-deep .form-box .el-upload--picture-card {
  width: $uploadWidth;
  height: $uploadHeight;
  border: none;
}
::v-deep .form-box .el-upload-list--picture-card .el-upload-list__item {
  width: $uploadWidth;
  height: $uploadHeight;
}
.uploadbg {
  width: $uploadWidth;
  height: $uploadHeight;
}
.uploader {
  display: flex;
  // align-items: center;
  flex-wrap: wrap;

  .upload-list {
    margin-right: 10px;
    margin-bottom: 10px;
    width: 294px;
    height: 165px;
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid #eee;
    position: relative;

    &:hover {
      .icon-container {
        display: block;
        transition: all 0.5s;
      }
    }

    .icon-container {
      position: absolute;
      display: none;
      transition: all 0.5s;
      width: 100%;
      height: 100%;
      line-height: 150px;
      color: #fff;
      font-size: 20px;
      text-align: center;
      border-radius: 8px;
      top: 0;
      left: 0;
      background-color: rgba(0, 0, 0, 0.5);
      cursor: pointer;

      span {
        margin: 0 10px;
        cursor: pointer;
      }
    }
  }

  .imgs {
    position: absolute;
    top: 0;
    right: 0;
  }
}
</style>
